package com.luojing.proxy.p1;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**CGLLIB动态代理
 * @author luojing
 * @create 2018/08/31 上午9:35
 **/
public class CGLibHandler implements MethodInterceptor {

  private Object tar;

  public Object createObject(Object obj){
    this.tar = obj;

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(obj.getClass());
    enhancer.setCallback(this);
    Object proxy = enhancer.create();
    return proxy;
  }

  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    Object obj = null;
    //切面逻辑（advise），此处是在目标类代码执行之前
    System.out.println("---before intercept----");
    obj = method.invoke(tar, objects);
    System.out.println("---after intercept----");
    return obj;
  }
}
